package com.moshang.blog.controller.base;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.moshang.blog.core.annotation.SystemLog;
import com.moshang.blog.entity.vo.TableField;
import com.moshang.blog.entity.vo.TableVO;
import com.moshang.blog.poi.ExcelUtil;
import com.moshang.blog.service.TableService;

import com.moshang.blog.core.utils.PageUtil;
import com.moshang.blog.core.utils.StringUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @program: blog
 * @description: 数据库表管理
 * @author: xieweiwei
 * @create: 2018-10-10 18:17
 **/
@Controller
@RequestMapping("back/system/table")
public class TableController {
    private final Logger logger = LoggerFactory.getLogger(TableController.class);

    @Autowired
    private TableService tableService;
    /**
     *table
     * @return
     */
    @GetMapping("list")
    public String list(){
        return "back/system/table/list";
    }
    /***
     * 所有数据表分页查询
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @RequiresPermissions("sys:table:list")
    @GetMapping("listPage")
    @ResponseBody
    public PageUtil<TableVO> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                  @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                                  ServletRequest request){

        String searchKey=request.getParameter("searchKey");
        String searchValue=request.getParameter("searchValue");
        PageUtil<TableVO> pageUtils = new PageUtil<>();
        if (StringUtils.isBlank(searchValue)){
            searchKey=null;
        }
        Page<TableVO> tablePage = tableService.selectTablePage(new Page<>(page,limit),searchKey,searchValue);
        pageUtils.setCount((int) tablePage.getTotal());
        pageUtils.setData(tablePage.getRecords());
        return pageUtils;
    }

    /**
     * 导出数据
     * @return
     */
    @PostMapping("exportTable")
    @SystemLog("导出数据表")
    public void exportTable(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        List<TableVO> result = tableService.findAllTables(params);

        try {
            ExcelUtil.exportExcel(result,"数据库表","数据库表",TableVO.class,"数据库表",response);
        } catch (Exception e) {
            throw new RuntimeException("系统异常");
        } finally {
            try {

            } catch (Exception e) {
                throw new RuntimeException("系统异常");
            }
        }
    }
    @RequestMapping("addUI")
    public  String addUI(){
        return "back/system/table/add";
    }
    @GetMapping("editUI")
    @SystemLog("修改数据库表")
    public String edit(@RequestParam("name")String name,@RequestParam("type")String type, Model model){
        TableVO tableVO = tableService.detailTable(name);
        String[] comments = tableVO.getComment().split(",");
        tableVO.setComment(comments[0]);
        Integer tabletype = comments.length>1?Integer.valueOf(comments[1]):0;
        tableVO.setTabletype(tabletype);

        String base  = "id,create_by,create_time,update_by,update_time,is_activited";
        String tree  = "id,parent_id,level,parent_ids,sort,create_by,create_time,update_by,update_time,is_activited";

        List<String> allNames = Lists.newArrayList();
        for (TableField t : tableVO.getFieldList()){
            if(tabletype == 1){
                if(!base.contains(t.getName())){
                    changeTableField(t);
                    allNames.add(t.getName());
                }
            }
            if(tabletype == 2){
                if(!tree.contains(t.getName())){
                    changeTableField(t);
                    allNames.add(t.getName());
                }
            }
        }
        model.addAttribute("tableVO",tableVO);
        model.addAttribute("allNames", JSONObject.toJSONString(allNames));
        if (type.equals("edit")){
            return "back/system/table/edit";
        }else {
            return "back/system/table/show";
        }
    }
    private void changeTableField(TableField t){
        String[] c = t.getComment().split(",");
        t.setComment(c[0]);
        if(c.length>1) {
            t.setDofor(c[1]);
        }
        if(c.length>3){
            t.setDefaultValue(Boolean.valueOf(c[3]));
        }else {
            t.setDefaultValue(false);
        }
        if(c.length>4){
            t.setListIsShow(Boolean.valueOf(c[4]));
        }
        if(c.length>5){
            t.setListIsSearch(Boolean.valueOf(c[5]));
        }
    }
    @RequiresPermissions("sys:table:list")
    @PostMapping("showFields")
    @ResponseBody
    @SystemLog("请求字段展示数据(全部显示)")
    public PageUtil<TableField> showFields(@RequestParam(value = "s_name",required = false)String name,
                                           @RequestParam(value = "s_tableType",required = false)Integer tableType){
        PageUtil<TableField> tableLayerData = new PageUtil<>();
        if(StringUtils.isBlank(name)){
            return null;
        }
        if(tableType != 1 && tableType != 2 && tableType != 3){
            return null;
        }
        Map<String,Object> map = Maps.newHashMap();
        map.put("name",name);
        map.put("tableType",tableType);
        List<TableField> list = tableService.selectFields(map);
        for(TableField t : list){
            changeTableField(t);
        }
        tableLayerData.setData(list);
        tableLayerData.setCount(list.size());
        return tableLayerData;
    }
    /**
     * 生成代码
     */
    @RequestMapping("genCode")
    public void code(String tables, HttpServletResponse response) throws IOException {
        byte[] data = tableService.generatorCode(tables.split(","));

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"gen.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }
}
